<!-- Main.vue -->
<template>
  <div class="main-container">
    <!-- 顶部 -->
    <div class="header">
      <div class="header-left">
        <div class="collapse-btn-wrapper" @click="toggleCollapse">
          <div class="collapse-btn-inner" :class="{ 'is-collapsed': isCollapsed }">
            <el-icon class="collapse-icon"><ArrowLeft /></el-icon>
          </div>
        </div>
        <div class="logo-container">
          <img src="@/assets/images/logo.png" alt="Logo" class="logo" />
        </div>
        <h2 class="site-title">企业信息筛查系统</h2>
      </div>
      
      <div class="header-right">
        <el-dropdown trigger="click" @command="handleCommand" class="user-dropdown-container">
          <div class="avatar-wrapper">
            <el-avatar :size="40" src="/images/avatar.png" class="user-avatar" />
            <el-icon class="dropdown-icon"><CaretBottom /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu class="custom-dropdown">
              <div class="user-info-card">
                <div class="info-header">
                  <el-avatar :size="50" src="/images/avatar.png" />
                <div class="user-details">
                  <span class="user-phone">{{ userInfo?.phone || '未登录' }}</span>
                  <span class="user-type">{{ userTypeText }}</span>
                </div>
                </div>
                <div class="info-stats">
                  <div class="stat-item">
                    <el-icon><Ticket /></el-icon>
                    <div class="stat-content">
                      <span class="stat-label">使用状态</span>
                      <span class="stat-value">{{ usageStatusText }}</span>
                    </div>
                  </div>
                  <div class="stat-item">
                    <el-icon><Timer /></el-icon>
                    <div class="stat-content">
                      <span class="stat-label">服务状态</span>
                      <span class="stat-value">{{ serviceStatusText }}</span>
                    </div>
                  </div>
                </div>
                <div class="dropdown-actions">
                  <el-button type="primary" @click="goToSetPassword" class="action-btn">
                    <el-icon><Edit /></el-icon>修改密码
                  </el-button>
                  <el-button type="danger" @click="handleLogout" class="action-btn">
                    <el-icon><SwitchButton /></el-icon>退出登录
                  </el-button>
                </div>
              </div>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 左侧导航 -->
    <div class="nav-container" :class="{ 'is-collapsed': isCollapsed }">
    <el-menu
      class="nav-menu"
      :default-active="$route.path"
      router
      :collapse="isCollapsed"
        :collapse-transition="false"
      >
        <el-menu-item v-for="(item, index) in menuItems" 
          :key="index" 
          :index="item.path" 
          class="menu-item"
        >
          <el-icon><component :is="item.icon" /></el-icon>
          <template #title>
            <span class="menu-text">{{ item.title }}</span>
          </template>
      </el-menu-item>
    </el-menu>
    </div>

    <!-- 右侧主内容区域 -->
    <div class="main-content" :class="{ 'content-collapsed': isCollapsed }">
      <router-view v-slot="{ Component }">
        <transition name="fade" mode="out-in">
          <keep-alive>
            <component :is="Component" />
          </keep-alive>
        </transition>
      </router-view>
    </div>
    
    <!-- 浮动广告组件 -->
    <FloatingAd />
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch, onBeforeUnmount } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useUserStore } from '@/stores/user';
import { ElMessage } from 'element-plus';
import { getUserPackageApi } from '@/api/quota';
import FloatingAd from '@/components/FloatingAd.vue';
import {
  Document,
  Download,
  Wallet,
  Service,
  ArrowLeft,
  CaretBottom,
  Phone,
  Trophy,
  Ticket,
  Timer,
  Edit,
  SwitchButton
} from '@element-plus/icons-vue';

const router = useRouter();
const userStore = useUserStore();
const showMessage = ref(false);
const message = ref('');
const isCollapsed = ref(false);
const userInfo = computed(() => userStore.userInfo); // 使用computed确保响应式更新
const hasRedirected = ref(false);
const membershipInfo = computed(() => userStore.membershipInfo);
const packageInfo = ref({
  packageType: '',
  totalQuota: 0,
  usedQuota: 0,
  startTime: '',
  endTime: ''
});

// 计算用户类型文本
const userTypeText = computed(() => {
  const packageType = packageInfo.value.packageType;
  if (!packageType || packageType === '无套餐' || packageType === '') {
    return '免费用户';
  }
  return 'VIP用户';
});

// 计算使用状态文本（显示剩余额度）
const usageStatusText = computed(() => {
  const totalQuota = packageInfo.value.totalQuota || 0;
  const usedQuota = packageInfo.value.usedQuota || 0;
  const remainingQuota = Math.max(0, totalQuota - usedQuota);
  
  if (totalQuota === 0) {
    return '免费使用';
  }
  return `剩余 ${remainingQuota.toLocaleString()} 点`;
});

// 计算服务状态文本（显示剩余时长）
const serviceStatusText = computed(() => {
  if (!packageInfo.value.endTime) {
    return '永久有效';
  }
  
  const endTime = new Date(packageInfo.value.endTime);
  const currentDate = new Date();
  const timeDiff = endTime - currentDate;
  const remainingDays = Math.floor(Math.max(0, timeDiff / 86400000));
  
  if (remainingDays <= 0) {
    return '已过期';
  } else if (remainingDays < 30) {
    return `剩余 ${remainingDays} 天`;
  } else if (remainingDays < 365) {
    const months = Math.floor(remainingDays / 30);
    return `剩余 ${months} 个月`;
  } else {
    const years = Math.floor(remainingDays / 365);
    return `剩余 ${years} 年`;
  }
});
const menuItems = [
  { path: '/main/screening', title: '企业信息筛查', icon: Document },
  { path: '/main/export', title: '导出结果', icon: Download },
  { path: '/main/quota', title: '信息余额查询', icon: Wallet },
  { path: '/main/recharge', title: '套餐充值', icon: Trophy },
  { path: '/main/support', title: '推广返佣及联系客服', icon: Service },
];

const handleLogout = () => {
  userStore.logout();
  router.push('/');
};

const goToSetPassword = () => {
  router.push('/set-password');
  
  // 设置一个短时间后刷新用户信息的回调
  setTimeout(() => {
    refreshUserMembershipInfo();
  }, 3000); // 3秒后刷新，给用户足够时间修改密码
};

const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value;
};

const handleCommand = (command) => {
  switch (command) {
    case 'setPassword':
      goToSetPassword();
      break;
    case 'logout':
      handleLogout();
      break;
  }
};

// 通过watch监听路由变化时刷新用户信息
watch(
  () => router.currentRoute.value,
  async () => {
    await refreshUserMembershipInfo();
  }
);

// 封装刷新用户会员信息的方法
const refreshUserMembershipInfo = async () => {
  try {
    // 加载用户会员信息
    const response = await getUserPackageApi();
    if (response.data.code === 201) {
      ElMessage.error(response.data.data);
      // 即使出错，也设置默认值
      packageInfo.value = {
        packageType: '无套餐',
        totalQuota: 0,
        usedQuota: 0,
        startTime: '',
        endTime: ''
      };
      return;
    }
    
    // 确保响应数据存在
    if (response.data && response.data.data) {
      const data = response.data.data;
      packageInfo.value = {
        packageType: data.packageType || '无套餐',
        totalQuota: data.totalQuota || 0,
        usedQuota: data.usedQuota || 0,
        startTime: data.startTime || '',
        endTime: data.endTime || ''
      };
      
      // 从API响应中更新会员信息
      const updatedMembershipInfo = {
        packageType: packageInfo.value.packageType,
        remainingQuota: Math.max(0, packageInfo.value.totalQuota - packageInfo.value.usedQuota),
        remainingDays: 0
      };
      
      // 计算剩余天数
      if (packageInfo.value.endTime) {
        const endTime = new Date(packageInfo.value.endTime);
        const currentDate = new Date();
        const timeDiff = endTime - currentDate;
        updatedMembershipInfo.remainingDays = Math.floor(Math.max(0, timeDiff / 86400000));
      }
      
      // 直接更新store中的会员信息
      userStore.updateMembership(updatedMembershipInfo);
    } else {
      // 如果响应数据为空，设置默认值
      packageInfo.value = {
        packageType: '无套餐',
        totalQuota: 0,
        usedQuota: 0,
        startTime: '',
        endTime: ''
      };
    }
  } catch (error) {
    console.error('加载会员信息失败', error);
    // 出错时设置默认值
    packageInfo.value = {
      packageType: '无套餐',
      totalQuota: 0,
      usedQuota: 0,
      startTime: '',
      endTime: ''
    };
  }
};

// 组件挂载时刷新用户信息并添加事件监听器
onMounted(async () => {
  await refreshUserMembershipInfo();
  
  // 添加自定义事件监听器，当其他组件更新会员信息时自动响应
  window.addEventListener('membershipUpdated', (event) => {
    console.log('检测到会员信息更新:', event.detail);
  });
});

// 组件卸载时移除事件监听器
onBeforeUnmount(() => {
  window.removeEventListener('membershipUpdated', () => {});
});
</script>

<style lang="scss" scoped>
.main-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px;
  height: 70px;
  background: linear-gradient(135deg, #ffffff 0%, #f0f7ff 100%);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

  .header-left {
    display: flex;
    align-items: center;
    gap: 16px;
  }

  .site-title {
    font-size: 22px;
    background: linear-gradient(45deg, #1a73e8, #34a853);
    -webkit-background-clip: text;
    color: transparent;
    font-weight: 600;
    margin: 0;
    letter-spacing: 0.5px;
    white-space: nowrap;
  }
}

.collapse-btn-wrapper {
  cursor: pointer;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .collapse-btn-inner {
    width: 32px;
    height: 32px;
    border-radius: 8px;
    background: linear-gradient(135deg, #f0f7ff 0%, #e6f0ff 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    
    &:hover {
      transform: scale(1.05);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    &.is-collapsed {
      .collapse-icon {
        transform: rotate(180deg);
      }
    }

    .collapse-icon {
      font-size: 18px;
      color: #1a73e8;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    }
  }
}

.logo-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 50px;
  padding: 0 2px;
}

.logo {
  width: 70px;
  height: 50px;
  object-fit: contain;
}

.avatar-wrapper {
  display: flex;
  align-items: center;
  gap: 4px;
  cursor: pointer;
  padding: 4px;
  border-radius: 24px;
  transition: all 0.3s ease;

  &:hover {
    background-color: rgba(0, 0, 0, 0.04);
}

.user-avatar {
    border: 2px solid #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }

  .dropdown-icon {
    color: #606266;
    font-size: 12px;
    transition: transform 0.3s ease;
  }

  &:hover .dropdown-icon {
    transform: translateY(2px);
  }
}

.custom-dropdown {
  margin-top: 8px !important;
  padding: 0 !important;
  border-radius: 12px !important;
  overflow: hidden;
  min-width: 300px !important;

  .user-info-card {
    padding: 20px;

    .info-header {
      display: flex;
      align-items: center;
      gap: 16px;
      margin-bottom: 20px;

      .user-details {
        display: flex;
        flex-direction: column;
        gap: 4px;

        .user-phone {
          font-size: 16px;
          font-weight: 600;
          color: #1f2937;
        }

        .user-type {
    font-size: 14px;
          color: #1a73e8;
        }
      }
    }

    .info-stats {
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 16px;
      margin-bottom: 20px;
      padding: 16px;
      background: #f8fafc;
      border-radius: 8px;

      .stat-item {
        display: flex;
        align-items: center;
        gap: 12px;

        .el-icon {
          font-size: 20px;
          color: #1a73e8;
        }

        .stat-content {
          display: flex;
          flex-direction: column;
          gap: 2px;

          .stat-label {
            font-size: 12px;
            color: #64748b;
          }

          .stat-value {
            font-size: 16px;
            font-weight: 600;
            color: #1f2937;
          }
        }
      }
    }

    .dropdown-actions {
      display: flex;
      gap: 12px;

      .action-btn {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 6px;
        height: 36px;
        border-radius: 8px;
        font-size: 14px;

        .el-icon {
          font-size: 16px;
        }
      }
    }
  }
}

.nav-container {
  position: fixed;
  top: 70px;
  left: 0;
  bottom: 0;
  width: 240px;
  background: #ffffff;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.05);
  z-index: 900;

  &.is-collapsed {
    width: 64px;

    :deep(.el-menu) {
      width: 64px;
    }

    :deep(.el-menu-item) {
      padding: 0 !important;
      margin: 8px 0 !important;
      width: 100% !important;

      .el-icon {
        margin: 0 !important;
      }

      .el-tooltip {
        padding: 0 !important;
        width: 100% !important;
        justify-content: center !important;
      }
    }
  }
}

.nav-menu {
  border-right: none;
  background: transparent;
  margin-top: 12px;
  width: 100%;

  :deep(.el-menu-item) {
    display: flex;
    align-items: center;
    padding: 0 16px;
    margin: 8px 12px;
    height: 48px;
    line-height: 48px;
    border-radius: 8px;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

    .el-tooltip {
      display: flex;
      align-items: center;
      width: 100%;
    }

    &:hover {
      background: linear-gradient(90deg, rgba(26, 115, 232, 0.08) 0%, rgba(26, 115, 232, 0.04) 100%);
      
      .el-icon, .menu-text {
        color: #1a73e8;
      }
    }

    &.is-active {
      background: linear-gradient(90deg, #1a73e8 0%, #3182f6 100%);
      
      .el-icon, .menu-text {
        color: #ffffff;
      }
    }

    .el-icon {
      font-size: 18px;
      color: #64748b;
      transition: all 0.3s ease;
      margin-right: 12px;
    }

    .menu-text {
      font-size: 14px;
      color: #64748b;
      transition: all 0.3s ease;
    }
  }
}

.main-content {
  margin-left: 240px;
  margin-top: 70px;
  padding: 24px;
  min-height: calc(100vh - 70px);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

  &.content-collapsed {
    margin-left: 64px;
  }
}

// 添加过渡动画样式
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>